Chapter 3: Conditions

Simple conditions

A lot of programming has to do with executing code if a particular condition holds. Here we give a brief overview of how you can express certain conditions in Python. Can you figure our what all of the conditions do?


In [ ]:
print(2 < 5)
print(2 <= 5)
print(3 > 7)
print(3 >= 7)
print(3 == 3)
print("school" == "school")
print("Python" != "perl")

The relevant 'logical operators' that we used here are: <, <=, >,>=,==,!=. In Python-speak, we say that such logical expression gets 'evaluated' when you run the code. The outcome of such an evaluation is a 'binary value' or a so-called 'boolean' that can take only two possible values: True or False. You can assign such a boolean to a variable:


In [ ]:
greater = (5 > 2)
print(greater)
greater = 5 < 2
print(greater)
print(type(greater))

if, elif and else

At the end of the previous chapter, we have talked about dictionaries, which are a kind of data structure which you will need a lot when writing Python. Recall our collection of good_reads from the previous chapter. Recall that we could use the key of an entry to retrieve the score of a book in our collection:


In [ ]:
good_reads = {"Emma":8, "Pride and Prejudice":10, "Sense and Sensibility":7, "Northanger Abbey":3}
score = good_reads["Sense and Sensibility"]
print(score)

At some point, however, we might forget which books we have already added to our collection. What happens if we try to get the score of a book that is not in our collection?


In [ ]:
score = good_reads["Moby Dick"]
print(score)

We get an error, and more specifically a KeyError, which basically means: "the key you asked me to look up is not in the dictionary...". We will learn a lot more about error handling later, but for now we would like to prevent our program from giving it in the first place. Let's write a little program that prints "X is in the collection" if a particular book is in the collection and "X is NOT in the collection" if it is not.


In [ ]:
book = "Moby Dick"
if book in good_reads:
    print(book + " is in the collection")
else:
    print(book + " is NOT in the collection")

A lot of new syntax here. Let's go through it step by step. First we check whether the value we assigned to book is in our collection. The part after if is a logical expression which will be True or False:


In [ ]:
print(book in good_reads)

Because our book is not in the collection, Python returns False. Let's do the same thing for a book that we know is in the collection:


In [ ]:
print("Emma" in good_reads)

Indeed, it is in the collection! Back to our if statement. If the expression after if evaluates to True, our program will go on to the next line and print book + " is in the collection". Let's try that as well:


In [ ]:
if "Emma" in good_reads:
    print("Found it!")

In [ ]:
if book in good_reads:
    print("Found it!")

Notice that the last print statement is not executed. That is because the value we assigned to book is not in our collection and thus the part after if did not evaluate to True. In our little program above we used another statement besides if, namely else. It shouldn't be too hard to figure out what's going on here. The part after else will be evaluated if the if statement evaluated to False. In English: if the book is not in the collection, print that is is not.

Indentation!

Unlike other languages, Python does not make use of curly braces to mark the start and end of pieces of code, like if-statements. The only delimiter is a colon (:) and the indentation of the code (i.e. the use of whitespace). This indentation must be used consistently throughout your code. The convention is to use 4 spaces as indentation. This means that after you have used a colon (such as in our if statement) the next line should be indented by four spaces. (The shortcut for typing these 4 spaces in many editors is inserting a TAB.)

Sometimes we have various conditions that should all evaluate to something different. For that Python provides the elif statement. We use it similar to if and else. Note however that you can only use elif after an if statement! Above we asked whether a book was in the collection. We can do the same thing for parts of strings or for items in a list. For example we could test whether the letter a is in the word banana:


In [ ]:
print("a" in "banana")

Likewise the following evaluates to False:


In [ ]:
print("z" in "banana")

Let's use this in an if-elif-else combination, a very common way to implement 'decision trees' in Python:


In [ ]:
word = "rocket science"
if "a" in word:
    print(word + " contains the letter a")
elif "s" in word:
    print(word + " contains the letter s")
elif "d" in word:
    print(word + " contains the letter s")
elif "c" in word:
    print(word + " contains the letter c")
else:
    print("What a weird word!")

First the if statement will be evaluated. Only if that statement turns out to be False the computer will proceed to evaluate the elif statement. If the elif statement in turn would prove to be False, the machine will proceed and execute the lines of code associated with the else statement. You can think of this coding structure as a decision tree! Remember: if somewhere along the tree, your machine comes across a logical expression which is true, it won't bother anymore to evaluate the remaining options!


DIY

Let's practice our new condition skills a little. Write a small program that defines a variable weight. If the weight is > 50 pounds, print "There is a $25 charge for luggage that heavy." If it is not, print: "Thank you for your business." If the weight is exactly 50, print: "Pfiew! The weight is just right!". Change the value of weight a couple of times to check whether your code works. (Tip: make use of the logical operators and if-elif-else tree! Make sure you use the correct indentation.)


In [ ]:
# insert your code here

and, or, not

Until now, our conditions consisted of single logical expresssions. However, quite often we would like to test for multiple conditions: for instance, you would like to tell your computer to do something if this and this were but this and that were not true. Python provides a number of ways to do that. The first is with the and statement which allows us to combine two expressions that need both to be true in order for the combination to be true. Let's see how that works:


In [ ]:
word = "banana"
if ("a" in word) or ("b" in word):
    print("Both a and b are in " + word)

Note how we can use round brackets to make the code more readable (but you can just as easily leave them out):


In [ ]:
word = "banana"
if ("a" in word) and ("b" in word):
    print("Both a and b are in " + word)

If one of the expressions evaluates to False, nothing will be printed:


In [ ]:
if ("a" in word) and ("z" in word):
    print("Both a and z are in " + word)

Now you know that the and operator exists in Python, you won't be too surprised to learn that there is also an or operator in Python that you can use. Replace and with or in the if statement below. Can you deduce what happens?


In [ ]:
word = "banana"
if ("a" in word) or ("z" in word):
    print("Both a and b are in " + word)

In the code block below, can you add an else statement that prints that none of the letters were found?


In [ ]:
if ("a" in word) and ("z" in word):
    print("a or z are in " + word)
else:
    print("None of these were found...")
# insert your code here

Finally we can use not to test for conditions that are not true.


In [ ]:
if ("z" not in word):
    print("z is not in " + word)

Objects, such as strings or integers of lists are True, simply because they exist. Empty strings, lists, dictionaries etc on the other hand are False because in a way they do not exist -- an empty list is not really a list, right? This principle is often by programmers to, for example, only execute a piece of code if a certain list contains anything at all:


In [ ]:
numbers = [1, 2, 3, 4]
if numbers:
    print("I found some numbers!")

Now if our list were empty, Python wouldn't print anything:


In [ ]:
numbers = [9,999]
if numbers:
    print("I found some numbers!")

DIY

  • Can you write code that prints "This is an empty list" if the provided list does not contain any values?

In [ ]:
numbers = []
# insert your code here
if not numbers:
    print("Is an empty list")
  • Can you do the same thing, but this time using the function len()?

In [ ]:
# insert your code here

What we have learnt

To finish this section, here is an overview of the new functions, statements and concepts we have learnt. Go through them and make sure you understand what their purpose is and how they are used.

  • conditions
  • indentation
  • if
  • elif
  • else
  • True
  • False
  • empty objects are false
  • not
  • in
  • and
  • or
  • multiple conditions
  • ==
  • <
  • >
  • !=
  • KeyError

Final Exercises Chapter 3

Inspired by Think Python by Allen B. Downey (http://thinkpython.com), Introduction to Programming Using Python by Y. Liang (Pearson, 2013). Some exercises below have been taken from: http://www.ling.gu.se/~lager/python_exercises.html.

  • Can you implement the following grading scheme in Python?

In [ ]:
# grading system
  • Can you spot the reasoning error in the following code?

In [ ]:
score = 98.0
if score >= 60.0:
    grade = 'D'
elif score >= 70.0:
    grade = 'C'
elif score >= 80.0:
    grade = 'B'
elif score >= 90.0:
    grade = 'A'
else:
    grade = 'F'
print(grade)
  • Write Python code that defines two numbers and prints the largest one of them. Use an if-then-else tree.

In [ ]:
# code

Congrats: you've reached the end of Chapter 3! Ignore the code block below; it's only here to make the page prettier.


In [1]:
from IPython.core.display import HTML
def css_styling():
    styles = open("styles/custom.css", "r").read()
    return HTML(styles)
css_styling()


Out[1]: